<script setup>
  import {productDetail, recommendPro, queryProComment} from '@/api/product'
  import {addCart} from '@/api/cart'
  import useCommodityStore from '@/store/modules/commodity'
  import useSettingStore from '@/store/modules/setting'
  import defaultGoodImg from '@/assets/image/default_good.png'
  import { showToast } from 'vant'
  import emptyComment from '@/assets/image/empty_comment.png'

  const router = useRouter()
  const useStore = useCommodityStore()
  const {proxy} = getCurrentInstance()
  const currency = ref(useSettingStore().global.currencySymbol || '')

  const detail = ref({images: []})
  // swiper
  const pageIndex = ref(0)
  // 购买量
  const num = ref(1)
  // 选中的sku
  const sku = ref({})
  // 选中要展示的产品图
  const proImg = ref(defaultGoodImg)
  // 推荐好物
  const recommendList = ref([])
  // 商品详情、评价
  const tabType = ref('detail')
  const tabList = shallowRef([
    {label: proxy.$t('order.detail'), type: 'detail'},
    {label: proxy.$t('order.comment'), type: 'comment'},
  ])
  const page = ref({
    pageNum: 1,
    pageSize: 100
  })
  const commentLoading = ref(false)
  const commentOb = ref({rows: [], total: 0})
  const show = ref(false)
  const previewImg = ref('')

  // 切换产品图
  watch(() => pageIndex.value, (val) => {
    proImg.value = detail.value.images[val]
  })

  watch(() => router.currentRoute?.value, val => {
    getDetail()
  }, {deep: true})
  // 商品详情
  function getDetail() {
    const {params={}} = router.currentRoute?.value
    productDetail(params.productId).then(res => {
      const {image, productAttr, productValue} = res.data
      if(image) res.data.images = image.split(',')
      if(productAttr.length) {
        // 默认选择规格第一个值
        // res.data.productAttr.forEach(it => {
        //   it.selectAttr = it.attrValueArr[0]
        // })
      }
      detail.value = res.data
      initSku()
    })
    // 推荐好物
    recommendPro({productId: params.productId}).then(res => {
      const {rows} = res
      if(rows.length) {
        rows.forEach(it => {
          it.images = it.image.split(',')
        })
      }
      recommendList.value = rows
    })
  }
  // 商品评价
  function getCommentList() {
    const {params={}} = router.currentRoute?.value
    commentLoading.value = true
    queryProComment(params.productId, page.value).then(r => {
      commentOb.value = {
        rows: r.rows,
        total: r.total
      }
      commentLoading.value = false
    })
  }
  // 预览评价图
  function preview(img) {
    show.value = true
    previewImg.value = img
  }
  // 切换详情和评价
  function changeTab(type) {
    if(tabType.value!==type) {
      page.value = {
        pageNum: 1,
        pageSize: 100
      }
      commentOb.value = {rows: [], total: 0}
      if(type==='comment') {
        getCommentList()
      }
    }
    tabType.value = type
  }
  /* ---下单和加购物车--- */
  // 计算选中的sku
  function initSku() {
    const {productAttr, productValue, images} = detail.value
    const selectSku = productAttr.map(it => it.selectAttr).join(',')
    sku.value = productValue[selectSku] || {}
    // 选中规格里的产品图
    proImg.value = sku.value.image || images[pageIndex.value] || ''
  }
  // 选择sku
  function selectSku(it, val) {
    // 选择及取消sku
    it.selectAttr = it.selectAttr===val?'':val
    initSku()
  }
  // 选择商品数量
  function changeNum(v) {
    // 至少选购一件商品
    if(num.value===1&&v==-1) return
    // 选购商品数不能超过库存
    if(num.value>=sku.value.stock&&v==1) return
    if(v>0) num.value++
    if(v<0) num.value--
  }
  // 立即购买or添加购物车
  function buyProduct(isNew) {
    const {productId} = detail.value
    const params = {
      productId,
      num: num.value,
      skuId: sku.value.skuId,
      isNew
    }
    if(!sku.value.skuId) return showToast(proxy.$t('commodity.skuTip'))
    addCart(params).then(r => {
      if(!isNew) {
        showToast(proxy.$t('commodity.joinSuc'))
        // 更新购物车数量
        useStore.getCart()
      } else {
        router.push({path:'/shopping', query: {cartIds: r.data}})
      }
    })
  }
  // 好物详情
  function toRouter(it) {
    router.push(`/product-detail/${it.productId}`)
  }

  getDetail()
</script>

<template>
  <div class="product-detail">
    <!-- <van-swipe class="com-swipe" indicator-color="white">
      <van-swipe-item v-for="(it, i) in detail.images" :key="i">
        <img :src="it" class="img"/>
      </van-swipe-item>
    </van-swipe> -->
    <div class="pro-img">
      <img class="m-img" :src="proImg"/>
      <div class="img-list">
        <img
          :class="['thub-img', pageIndex===i?'active':'']"
          :src="it"
          v-for="(it, i) in detail.images"
          :key="i"
          @click="pageIndex=i"
        />
      </div>
    </div>
    <div class="info-cell">
      <p class="p-title">{{detail.productName}}</p>
      <p class="intro">{{detail.introduce}}</p>
      <p class="price"><span>{{currency}}</span>{{sku.price || detail.minPrice}}</p>
      <div class="sku" v-if="detail.productAttr&&detail.productAttr.length">
        <div v-for="it in detail.productAttr" :key="it.attrId" class="mb10">
          <p class="sku-name">
            {{it.attrName}}：
            <span>{{it.selectAttr}}</span>
          </p>
          <div class="sku-list">
            <p
              v-for="(val, i) in it.attrValueArr"
              :key="i"
              :class="['sku-item','cursor-p', 'mb10', val===it.selectAttr?'active':'']"
              @click="selectSku(it, val)"
            >
              {{val}}
            </p>
          </div>
        </div>
      </div>
      <div class="buy-cell">
        <div class="c-box">
          <p>{{$t('commodity.num')}}：</p>
          <p>
            <span @click="changeNum(-1)">－</span>
            <span>{{num}}</span>
            <span @click="changeNum(1)">＋</span>
          </p>
        </div>
        <van-button
          class="s-btn mb16"
          @click="buyProduct(1)"
          :disabled="sku.stock===0"
        >
          {{$t('commodity.buy')}}
        </van-button>
        <van-button class="s-btn c-gray" @click="buyProduct(0)">{{$t('commodity.joinCart')}}</van-button>
      </div>
    </div>
    <div class="comment-detail">
      <div class="tab">
        <p
          v-for="it in tabList"
          :key="it.type"
          :class="['tab-item', it.type===tabType?'active':'']"
          @click="changeTab(it.type)"
        >{{ it.label }}</p>
      </div>
      <div v-html="detail.detail" v-if="tabType==='detail'"/>
      <div class="comment" v-else>
        <div class="comment-item" v-for="item in commentOb.rows">
          <div class="user-score flex-bt">
            <p>{{ item.commentUser }}</p>
            <van-rate v-model="item.score" :allow-half="true" readonly/>
          </div>
          <div class="time-sku flex-bt">
            <p>{{ item.commentTime }}</p>
            <p>{{ item.productSku }}</p>
          </div>
          <div class="content">{{ item.comment }}</div>
          <div class="img-cell">
            <img
              @click="preview(img)"
              v-for="img in item.imageUrlSet"
              :src="img"
            />
          </div>
        </div>
        <div class="comment-empty" v-if="!commentLoading&&!commentOb.total">
          <img :src="emptyComment"/>
          <p>{{$t('order.noComment')}}~</p>
        </div>
      </div>
    </div>
    <div class="recommend" v-if="recommendList.length">
      <p class="r-title">{{$t('commodity.recommendGood')}}</p>
      <div class="group-list">
        <van-row :gutter="[9, 16]">
          <van-col
            span="12"
            class="l-item"
            v-for="it in recommendList"
            :key="it.productId"
            @click="toRouter(it)"
          >
            <img :src="it.images[0]" alt=""/>
            <p class="c-name text-overflow">{{it.productName}}</p>
            <p class="sub-name text-overflow">{{it.introduce}}</p>
            <p class="price">
              <span>{{currency}}{{it.minPrice}}</span>
              <!-- <span>{{currency}}{{pro.maxPrice}}</span> -->
            </p>
          </van-col>
        </van-row>
      </div>
    </div>
    <van-popup v-model:show="show"><img :src="previewImg"/></van-popup>
  </div>
</template>

<style scoped lang="scss">
  :deep(.van-popup--center) {
    max-width: 100%;
    background: none;
    img {
      width: 100%;
      height: auto;
    }
  }
  .product-detail  {
    padding: 16px;
    .mb16 {
      margin-bottom: 16px;
    }
    .mb10 {
      margin-bottom: 10px;
    }
    .com-swipe  {
      margin-bottom: 16px;
      img  {
        height: 388px;
        width: 100%;
      }
    }
    .pro-img {
      margin-bottom: 16px;
      .m-img {
        height: 388px;
        width: 100%;
      }
      .img-list {
        height: 54px;
        display: flex;
        align-items: center;
        justify-content: center;
        column-gap: 16px;
        overflow: scroll;
        scrollbar-width: none;
        &::-webkit-scrollbar {
          display: none;
        }
        .thub-img  {
          height: 30px;
          width: 30px;
          text-align: center;
          border-radius: 4px 4px 4px 4px;
          border: 1px solid #F7F7F7;
          &.active  {
            border: 1px solid #B24C49;
          }
        }
      }
    }
    .info-cell {
      padding-bottom: 16px;
      border-bottom: 1px #E5E5E5 solid;
      .p-title {
        font-size: 24px;
        margin-bottom: 4px;
      }
      .intro {
        font-size: 16px;
        color: #939599;
      }
      .price {
        font-size: 18px;
        font-weight: 600;
        margin: 16px 0;
      }
      .sku {
        .sku-name {
          color: #8C8C8C;
          font-size: 14px;
          margin-bottom: 8px;
          span {
            color: #262626;
          }
        }
        .sku-list {
          display: flex;
          gap: 10px;
          flex-wrap: wrap;
          .sku-item {
            height: 32px;
            line-height: 32px;
            border: 1px solid #8C8C8C;
            border-radius: 2px;
            color: #8C8C8C;
            font-size: 12px;
            padding: 0 20px;
            &.active {
              background: #262626;
              border: none;
              color: #FFFFFF;
            }
          }
        }
      }
      .buy-cell {
        .c-box {
          margin-bottom: 24px;
          margin-top: 20px;
          height: 35px;
          font-size: 12px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          p {
            font-size: 14px;
            color: #939599;
            &:nth-of-type(2) {
              border-radius: 2px;
              border: 1px #262626 solid;
              padding: 8px;
              span {
                font-size: 12px;
                &:first-child, &:last-child {
                  font-size: 16px;
                  display: inline-block;
                  height: 16px;
                  width: 16px;
                  text-align: center;
                  line-height: 16px;
                  border-radius: 50%;
                  background: #F5F5F5;
                  color: #A9A9B2;
                  &:hover {
                    cursor: pointer;
                  }
                }
                &:last-child {
                  background: #262626;
                  color: #FFFFFF;
                }
                &:nth-child(2) {
                  padding: 0 30px;
                  color: #8C8C8C;
                }
              }
            }
          }
        }
      }
    }
    .comment-detail {
      padding-top: 24px;
      .tab {
        display: flex;
        column-gap: 32px;
        margin-bottom: 24px;
        .tab-item {
          font-size: 16px;
          padding-bottom: 9px;
          &.active {
            font-weight: 600;
            border-bottom: 2px #262626 solid;
          }
        }
      }
      .comment  {
        .comment-item {
          font-size: 14px;
          padding-bottom: 24px;
          &:nth-child(n + 2) {
            padding-top: 24px;
            border-top: 1px #E5E5E5 solid;
          }
          :deep(.van-rate__icon--full) {
            color: #262626;
          }
          .time-sku  {
            font-size: 12px;
            margin-top: 4px;
            p:first-child {
              color: #8C8C8C;
            }
          }
          .content {
            margin-top: 16px;
          }
          .img-cell {
            display: flex;
            column-gap: 8px;
            row-gap: 8px;
            flex-wrap: wrap;
            margin-top: 12px;
            img {
              width: 109px;
              height: 109px;
              object-fit: cover;
            }
          }
        }
        .comment-empty {
          text-align: center;
          padding: 100px 0;
          img {
            width: 100px;
            height: 100px;
          }
          p {
            font-size: 14px;
            color: #8C8C8C;
          }
        }
      }
    }
    .recommend {
      margin:24px 0 40px;
      .r-title {
        font-size: 18px;
        color: #262626;
        margin-bottom: 32px;
        text-align: center;
      }
      .group-list {
        .l-item {
          border-radius: 4px;
          img {
            height: 190px;
            width: 100%;
            margin-bottom: 8px;
          }
          p {
            text-align: center;
          }
          .c-name {
            font-weight: 600;
            font-size: 14px;
            margin-bottom: 4px;
          }
          .sub-name {
            font-size: 12px;
            color: #939599;
            margin-bottom: 4px;
          }
          .price {
            font-weight: 600;
            font-size: 14px;
            span:first-child {
              font-weight: 600;
              font-size: 14px;
              color: #262626;
              margin-right: 4px;
            }
          }
        }
      }
    }
  }
</style>